package com.xlongwei.service;

import org.noear.snack.ONode;
import org.noear.solon.annotation.Controller;
import org.noear.solon.annotation.Init;
import org.noear.solon.annotation.Mapping;
import org.noear.wood.DataList;
import org.noear.wood.DbContext;
import org.noear.wood.annotation.Db;

import com.xlongwei.util.CardBin;

import cn.hutool.core.util.StrUtil;

@Controller
@Mapping("service/bankCard")
public class BankCard {
    @Db
    DbContext db;
    CardBin cardBin;

    @Init
    public void init() throws Exception {
        cardBin = new CardBin();
        DataList list = db.table("bank_card").selectDataList("cardBin");
        list.forEach(item -> {
            cardBin.add(item.getString("cardBin"));
        });
    }

    @Mapping
    public ONode bankCard(String bankCardNumber) throws Exception {
        ONode n = new ONode();
        String bin = cardBin.bin(bankCardNumber);
        if (StrUtil.isNotBlank(bin)) {
            DataList list = db.table("bank_card").whereEq("cardBin", bin)
                    .selectDataList(
                            "cardBin,issuerCode as bankId,issuerName as bankName,cardName,cardDigits,cardType,bankCode,bankName as bankName2");
            list.forEach(item -> {
                n.set("cardBin", item.get("cardBin"));
                n.set("bankId", item.get("bankId"));
                n.set("bankName", item.get("bankName"));
                n.set("cardName", item.get("cardName"));
                n.set("cardDigits", item.get("cardDigits"));
                n.set("cardType", item.get("cardType"));
                n.set("bankCode", item.get("bankCode"));
                n.set("bankName2", item.get("bankName2"));
            });
        }
        return n;
    }
}
